﻿using LitJson;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;

public delegate void HttpResponseHandler(bool success, string response, string msg, string json);

public delegate void HttpImageCallback(Sprite sprite);

public class HttpHelper : MonoBehaviour
{

    #region 单例
    private static HttpHelper _instance;
    public static HttpHelper Instance
    {
        get
        {
            if (_instance == null)
            {
                GameObject go = new GameObject("HttpHelper");
                _instance = go.AddComponent<HttpHelper>();
                DontDestroyOnLoad(go);
            }
            return _instance;

        }
    }

    void Start()
    {
        _instance = this;

    }

    #endregion

    public static string APIServer = "http://192.168.1.175:81/api/";
    public static string Token = "";
    private static readonly object locker = new object();
    public void Init(string serverURL = "")
    {

        if (serverURL.Substring(serverURL.Length - 1, 1) == "/")
        {
            serverURL = serverURL.Substring(0, serverURL.Length - 1);
        }
        Debug.Log("" + serverURL);
        APIServer = serverURL;
    }

    public void Post(string url, HttpResponseHandler callback, BaseHttpRequestVo data = null)
    {
        StartCoroutine(_post(url, callback, data));
    }

    public IEnumerator _post(string url, HttpResponseHandler callback, BaseHttpRequestVo postData)
    {
        WWWForm form = new WWWForm();
        string postStr = "";
        if (postData != null)
        {
            postStr = postData.ToJson();
            JsonData jd = JsonMapper.ToObject(postData.ToJson());
            foreach (var item in jd.Keys)
            {
                if (jd[item].IsInt)
                {
                    form.AddField(item, int.Parse(jd[item].ToString()));
                }
                else
                {
                    form.AddField(item, jd[item].ToString());
                }
            }
        }
        else
        {
            postStr = null;
        }
        bool success = false;
        string msg = "";
        string json = "";
        string response = "";
        JsonData data;
        using (UnityWebRequest wr = UnityWebRequest.Post(url, form))
        {
            wr.SetRequestHeader("Authorization", "Bearer " + Token);
            yield return wr.SendWebRequest();
            response = wr.downloadHandler.text;

            if (wr.responseCode == 0)
            {
                success = false;
                msg = "服务器无响应!";
            }
            else if (wr.responseCode == 200)
            {
                Debug.Log(wr.downloadHandler.text);
                data = JsonMapper.ToObject(wr.downloadHandler.text.Trim());
                if (int.Parse(data["result"].ToString()) == 1)
                {
                    success = true;
                    msg = data["msg"].ToString();
                    if (!data.Keys.Contains("response"))
                    {
                        json = "";
                    }
                    else
                    {
                        json = data["response"].ToJson();
                    }
                }
                else
                {
                    success = false;
                    msg = data["msg"].ToString();
                }

            }
            else if (wr.responseCode == 404)
            {
                success = false;
                msg = "接口异常或不存在!";
                json = "";
            }
            else if (wr.responseCode == 500)
            {
                success = false;
                msg = "服务器内部异常!";
                json = "";
            }
            wr.Dispose();
        }
        lock (locker)
        {
            Debug.Log("[HttpHelper]" + url+ "              form:" + postStr);
            Debug.Log("---response:" + response);
        }
        if (callback != null)
        {
            callback(success, response, msg, json);
        }
    }

    public void SendRequest(string apiName, HttpResponseHandler handler, BaseHttpRequestVo reqeustVo = null)
    {
        this.Post(APIServer + apiName, handler, reqeustVo);
    }
}